package service

import (
	"errors"
	"fmt"
	"github.com/gorilla/websocket"
	"html3/internal/client"
	"html3/internal/container"
	"html3/internal/syserror"
	"log"
)

// BindGroups 绑定组
func BindGroups(sc *container.ServiceContainer) error {
	// 检查clientId是否有对应的conn
	_, err := sc.Clients.Get(sc.ClientId)
	if err != nil {
		return err
	}
	if err := sc.GroupClients.Set(sc.GroupName, sc.ClientId, sc.Clients.C[sc.ClientId]); err != nil {
		return err
	}
	return nil
}

// DeleteClientFromGroupsByClientId 从groups删除
func DeleteClientFromGroupsByClientId(clientId string, gc *client.GroupClients) error {
	if err := gc.Del(clientId); err != nil {
		return err
	}
	return nil
}

func GetConnsFromGroups(groupName string, gc *client.GroupClients) ([]*websocket.Conn, error) {
	conns, err := gc.Get(groupName)

	return conns, err
}

func SendMessageGroup(sc *container.ServiceContainer) []error {
	conns, err := GetConnsFromGroups(sc.GroupName, sc.GroupClients)
	// 如果是群组不存在的错误，则不做处理
	if errors.Is(err, syserror.ErrGroupNotFound) {
		return nil
	}
	if err != nil {
		// 记录日志
		//return errors
	}
	var myErrors []error
	for _, conn := range conns {
		if err := conn.WriteMessage(websocket.TextMessage, []byte(sc.Message)); err != nil {
			log.Printf("conn.WriteMessage err %v\n", err)
			myErrors = append(myErrors, fmt.Errorf("conn.WriteMessage err %v\n", err))
		}
	}
	if len(myErrors) > 0 {
		return myErrors
	}
	return nil
}
